#!/bin/bash
#
# s3-del-old
#
# Script's documentation page: http://www.adminbuntu.com/delete_stale_s3_objects
#
# Deletes stale objects in a specified bucket on Amazon AWS S3.
#
#
# Copyright 2013 Andrew Ault
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software
# and associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

 
usage (){
  echo " "
  echo Usage: s3-del-old "bucketname" "time"
  echo Example: s3-del-old \"mybucket\" \"30 days\"
  echo " "
  echo "Do not include a leading slash in bucketname."
  echo " "
}
 
# if incorrect # parameters, show usage
if [ $# -lt 2 ]; then
  usage
  exit 2
elif [ $# -gt 2 ]; then
  usage
  exit 2
fi
 
# don't allow leading slash in bucketname
firstchar=${1:0:1}
if [ $firstchar = "/" ]; then
  echo "ERROR: Do not start bucketname with a slash."
  usage
exit 2
fi
 
# don't allow "s3:" in beginning of filename
teststring=${1:0:3}
teststring=${teststring,,}
if [ $teststring = "s3:" ]; then
  echo "ERROR: Do not start bucketname with \"s3:\""
  usage
exit 2
fi
 
# transform first parameter into fully formed s3 bucket parameter with trailing slash star
target='s3://'${1%/}'/*'
 
# translate the date string entered on the command line to unixtime
older_than_unixtime=`date -d"-$2" +%s`
 
# loop through a list of bucket objects
s3cmd ls $target | while read -r line;
do
  create_date=`echo $line | awk '{print $1,$2}'`
  create_date_unixtime=`date -d"$create_date" +%s`
  if [[ $create_date_unixtime -lt $older_than_unixtime ]]
  then
    filename=`echo $line|awk '{print $4}'`
    if [[ $filename != "" ]]
    then
      echo deleting $filename $create_date
      s3cmd del $filename
    fi
  fi
done;
